import Cookies from 'js-cookie';
import http from './http';

let API_URL = {
  GetBankID: 'card/unit/GetChooseBank',
  LogCardSearch: 'log/card/search',
  Root: '',
  appendListPersonInfos: 'card/personInfo/appendDataList',
  appendListPoliceInfos: 'card/policeInfos/appendDataList',
  YBData: 'card/YB/GetPersonData',
  YBList: 'card/YB/GetPersonList',
  YBUnitList: 'card/YB/GetYBUnitList',
  SyncYBData: 'card/YB/SyncYBData',
  SyncYBToDBState: 'card/YB/GetSyncYBToDBState',
};

API_URL = new Proxy(API_URL, {
  get: (t, p) =>
    (type => type === 'string' || type === 'number')(typeof t[p])
      ? '/SERVERAPI/'.concat(t[p])
      : t[p],
});

async function getCsrfToken() {
  try {
    let token = Cookies.get('csrfToken');
    if (!token) {
      const response = await http.get(API_URL.Root, { credentials: 'include' });
      token = Cookies.get('csrfToken');
    }

    if (!token) {
      return false;
    }

    return token;
  } catch (ex) {
    return false;
  }
}

/**
 * Log 记录日志的信息
 * @param card 身份证
 * @param type 类型
 * @param data json数据
 * @returns {Promise<boolean>}
 * @constructor
 */
export async function LogAddCardSearch(card, type, data) {
  try {
    const token = await getCsrfToken();

    if (!token) {
      return false;
    }

    await http.postJson(API_URL.LogCardSearch.concat(`?_csrf=${token}`), {
      card,
      type,
      data,
    });

    return true;
  } catch (ex) {
    console.log(ex);
    return false;
  }
}
